package com.basics.organization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.basics.api.response.organization.*;
import com.basics.channel.service.CyChannelGroupUserService;
import com.basics.common.exception.CustomException;
import com.basics.common.utils.AsyncUtil;
import com.basics.organization.entity.CyOrganization;
import com.basics.organization.entity.CyOrganizationGroup;
import com.basics.organization.entity.CyOrganizationUser;
import com.basics.organization.mapper.CyOrganizationMapper;
import com.basics.organization.mapper.CyOrganizationUserMapper;
import com.basics.organization.service.CyOrganizationGroupService;
import com.basics.organization.service.CyOrganizationService;
import com.basics.organization.service.CyOrganizationUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户组织绑定表 服务实现类
 * </p>
 *
 * @author WangWei
 * @since 2025-03-09
 */
@Service
public class CyOrganizationUserServiceImpl extends ServiceImpl<CyOrganizationUserMapper, CyOrganizationUser> implements CyOrganizationUserService {

    @Resource
    private CyOrganizationMapper cyOrganizationMapper;
    @Autowired
    private CyOrganizationGroupService cyOrganizationGroupService;
    @Autowired
    private CyChannelGroupUserService cyChannelGroupUserService;

    @Override
    public DefaultOrganizationInfoData getDefaultOrganization(Long userId){
        CyOrganizationUser cyOrganizationUser = getOne(new QueryWrapper<CyOrganizationUser>()
                .eq("user_id",userId).orderByDesc("default_flag").last("limit 1"));
        if(cyOrganizationUser==null){
            return null;
        }
        CyOrganization organization = cyOrganizationMapper.selectById(cyOrganizationUser.getOrganizationId());
        if(organization==null){
            return null;
        }
        DefaultOrganizationInfoData data = new DefaultOrganizationInfoData();
        BeanUtils.copyProperties(organization,data);
        return data;
    }

    @Override
    public CyOrganizationUser getByUserId(Long userId, Long organizationId){
        return getOne(new QueryWrapper<CyOrganizationUser>()
                .eq("user_id",userId).eq("organization_id",organizationId).eq("del_flag",0));
    }

    @Override
    public List<OrganizationListData> selectJoinOrganizationList(Long userId){
        return baseMapper.selectJoinOrganizationList(userId);
    }

    @Override
    @Transactional
    public void checkOrganization(Long organizationId,Long userId){
        CyOrganization organization = cyOrganizationMapper.selectById(organizationId);
        if(organization==null){
            throw new CustomException("组织ID错误");
        }
        CyOrganizationUser cyOrganizationUser = getByUserId(userId,organizationId);
        if(cyOrganizationUser==null){
            CyOrganizationGroup group = cyOrganizationGroupService.getDefaultGroup(organizationId);
            cyOrganizationUser = new CyOrganizationUser();
            cyOrganizationUser.setUserId(userId);
            cyOrganizationUser.setOrganizationId(organizationId);
            cyOrganizationUser.setDefaultFlag(false);
            if(group!=null){
                cyOrganizationUser.setGroupId(group.getId());
            }
            cyOrganizationUser.setOrganizationId(organizationId);
            save(cyOrganizationUser);
        }
        if(cyOrganizationUser.getDefaultFlag()){
            return;
        }
        List<CyOrganizationUser> cyOrganizationUsers = list(new QueryWrapper<CyOrganizationUser>()
                .eq("user_id",userId)
                .eq("del_flag",0));
        if(CollectionUtils.isNotEmpty(cyOrganizationUsers)){
            for (CyOrganizationUser v : cyOrganizationUsers) {
                if(v.getOrganizationId().equals(organizationId)){
                    v.setDefaultFlag(true);
                }else{
                    v.setDefaultFlag(false);
                }
            }
            updateBatchById(cyOrganizationUsers);
        }
        AsyncUtil.runAsync(()->{
            cyChannelGroupUserService.addAllChannelByOrganizationId(organizationId,userId);
        });
    }

    @Override
    public boolean checkHasJoinOrganization(Long id,Long userId){
        return count(new QueryWrapper<CyOrganizationUser>().eq("user_id",userId)
                .eq("organization_id",id)
                .eq("del_flag",0))>0;
    }

    @Override
    public int getJoinMemberNum(Long id){
        return count(new QueryWrapper<CyOrganizationUser>().eq("organization_id",id)
                .eq("del_flag",0));
    }

    @Override
    public int getDefaultJoinMemberNum(Long id){
        return count(new QueryWrapper<CyOrganizationUser>().eq("organization_id",id)
                .isNull("group_id")
                .eq("del_flag",0));
    }

    @Override
    public long getGroupMemberNum(String groupId){
        return count(new QueryWrapper<CyOrganizationUser>().eq("group_id",groupId)
                .eq("del_flag",0));
    }

    @Override
    public IPage<OrganizationMemberListData> selectJoinOrganizationMemberList(Page page,Long organizationId,String groupId){
        return baseMapper.selectJoinOrganizationMemberList(page,organizationId,groupId);
    }

    @Override
    public IPage<GroupOrganizationMemberListData> selectGroupOrganizationMemberList(Page page, Long organizationId,String searchText){
        return baseMapper.selectGroupOrganizationMemberList(page,organizationId,searchText);
    }

    @Override
    public List<GroupOrganizationListData> selectGroupList(Long organizationId){
        List<GroupOrganizationListData> list=  baseMapper.selectGroupList(organizationId);
        if(CollectionUtils.isEmpty(list)){
            list= new ArrayList<>();
        }
        return list;
    }

    @Override
    public List<String> selectOrganizationUserList(Long organizationId){
        List<CyOrganizationUser> cyOrganizationUsers = list(new QueryWrapper<CyOrganizationUser>()
                .eq("organization_id",organizationId)
                .eq("del_flag",0));
        if(CollectionUtils.isEmpty(cyOrganizationUsers)){
            return new ArrayList<>();
        }
        return cyOrganizationUsers.stream().map(v->v.getUserId().toString()).collect(Collectors.toList());
    }
}
